package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.consts.GmallConsts;
import com.atguigu.gmall.order.interceptor.LoginInterceptor;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.order.vo.OrderConfirmVO;
import com.atguigu.gmall.order.vo.OrderSubmitVO;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/")
public class OrderController {
    @Resource
    OrderService orderService;
    @PostConstruct
    public void init(){
        //加载要秒杀的商品信息初始化
        String skuId = 1001+"";
        int count = 10;//参与秒杀的数量
        RSemaphore semaphore = redissonClient.getSemaphore("sec:sem:" + skuId);
        semaphore.trySetPermits(count);
    }
    @Resource
    RabbitTemplate rabbitTemplate;
    @ApiOperation("秒杀接口")
    @GetMapping("seckill/{skuId}")
    public String secKill(@PathVariable("skuId")String skuId){
        Long userId = LoginInterceptor.getUserId();
        //获取秒杀商品的分布式信号量
        RSemaphore semaphore = redissonClient.getSemaphore("sec:sem:" + skuId);
        boolean flag = semaphore.tryAcquire();//如果RSemaphore中数量>0返回true同时 数量-1 如果数量<=0返回false
        if(flag){
            //秒杀锁定资源成功
            Map<String,Object> map = new HashMap<>();
            String orderToken = IdWorker.getIdStr();
            map.put("orderToken" , orderToken);
            map.put("userId",userId);
            map.put("skuId",skuId);
            //创建一个闭锁：让用户支付接口访问时阻塞
            RCountDownLatch cdl = redissonClient.getCountDownLatch("sec:cdl:" + orderToken);
            cdl.trySetCount(1);
            rabbitTemplate.convertAndSend(GmallConsts.MQ_ORDER_EXCHANGE,
                    "sec.kill" ,map );

            return "redirect:/seckill/pay/"+orderToken;
        }else{
            return "秒杀失败";
        }


    }
    @Resource
    RedissonClient redissonClient;
    @ApiOperation("秒杀支付接口")
    @GetMapping("seckill/pay/{orderToken}")
    public String secKillpay(@PathVariable("orderToken")String orderToken) throws InterruptedException {

        RCountDownLatch cdl = redissonClient.getCountDownLatch("sec:cdl:" + orderToken);
        cdl.await();//cdl的count值为0时一直阻塞
        //执行后续的支付业务
        return "";
    }




    @ResponseBody
    @ApiOperation("提交订单")
    @PostMapping("/submit")
    public ResponseVo<String> submit(@RequestBody OrderSubmitVO submitVO){
//        System.out.println(submitVO);
        String orderToken = null;
        try {
            orderToken = orderService.createOrder(submitVO);
        } catch (Exception e) {
            return ResponseVo.fail(e.getMessage());
        }
        return ResponseVo.ok(orderToken);
    }
    @ApiOperation("订单结算页")
    @GetMapping("/confirm")
    public String confirm(Model model){
        OrderConfirmVO orderConfirmVO = orderService.queryOrderConfirmVO();
        model.addAttribute("confirmVo",orderConfirmVO);
        return "trade";
    }
}
